<template>
  <tree-transfer-tag
    v-if="formItem"
    v-bind="{ ...tagConfig }"
    @click-input="clickInput"
    :selectedList="selectedList"
  />
  <tree-transfer-dialog
    ref="transferRef"
    v-bind="{ ...dialogConfig }"
    :treeData="treeData"
    :selectType="selectType"
    :nodeKey="nodeKey"
    @transferConfirm="transferConfirm"
  />
</template>
<script setup>
import { setTreeIds, removeEmptyChildren, flatten, checkArrLegal } from '@/utils';
import { apiMethods } from '@/utils/http';
import { ElMessage } from 'element-plus';

import TreeTransferTag from './TreeTransferTag.vue';
import TreeTransferDialog from './TreeTransferDialog.vue';
const props = defineProps({
  formItem: { type: Boolean, default: true },

  tagConfig: { type: Object, default: () => {} },
  dialogConfig: { type: Object, default: () => {} },
  singleCheck: { type: Boolean, default: false },
  requestUrl: { type: String, default: '' },
  requestParams: { type: Object, default: () => {} },

  selectType: { type: String, default: '3' },
  nodeKey: { type: String, default: 'id' },
  // 若接口需处理层级或选择对象，请传入
  tier: { type: String, default: 'data.data' },
  modelValue: { type: Array, default: () => [] },
});
const emit = defineEmits(['update:modelValue', 'itemEvent']);

// ref
const transferRef = ref();

const treeData = ref([]);
const flattenTreeList = ref([]);

// 已选择列表
const selectedList = ref([]);

const init = () => {
  getTreeList();
};

const getTreeList = async () => {
  transferRef.value.loading = true;
  let res = await apiMethods.post(props.requestUrl, props.requestParams);
  let code = res.data.code || res.data.errorCode;
  if (code === '200') {
    const tierArr = props.tier.split('.');
    let arr = res;
    tierArr.forEach(i => {
      arr = arr[i];
    });
    // 清除空children
    arr = removeEmptyChildren(arr);

    // 如果 nodeKey === frontId 则前端生成的frontId
    if (props.nodeKey === 'frontId') {
      setTreeIds(arr[0]);
      setTreeIds(arr[1]);
    }

    // 如果是单选，禁用无效选项
    props.singleCheck && traverseTree(arr);

    treeData.value = [...arr];
    flattenTreeList.value = flatten(treeData.value);

    // 验证数据合法性
    if (checkArrLegal(flattenTreeList.value, props.nodeKey)) {
      clearAll();
      closeDialog();
      return console.error('Data has duplicate nodeKey');
    }

    transferRef.value.init();
    transferRef.value.loading = false;
  }
};

const transferConfirm = tags => {
  selectedList.value = [...tags];

  let val = [];
  tags.forEach(item => val.push(item.id));
  emit('update:modelValue', val);
  // emit('itemEvent', {
  //   // value,
  //   eventName: 'confirm',
  //   // prop,
  //   treeData: treeData.value,
  //   flattenTreeList: flattenTreeList.value,
  //   selectedList: selectedList.value,
  // });
};

function traverseTree(tree) {
  tree.forEach(node => {
    if (node.type === props.selectType) {
      node.disabled = false;
    } else {
      node.disabled = true;
    }
    if (node.children) {
      traverseTree(node.children);
    }
  });
}

const clickInput = () => {
  init();
};

defineExpose({ init });
</script>
<style lang="scss" scoped></style>
